//axios封装post请求
//请求的默认前缀 只要是发出去请求就会 默认带上这个前缀
axios.defaults.baseURL = '/api'

//设置默认请求头 异步的
axios.defaults.headers = {
    'X-Requested-With': 'XMLHttpRequest'
}

//设置超时请求时间
axios.defaults.timeout = 10000


function postRequst(url, data) {
    let result = axios({
        method: 'post',
        url: url,
        data: data,
        transformRequest: [function (data) {
            let ret = '';
            for (let i in data) {
                ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + "&";
            }
            return ret;
        }],
        header: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).then(resp => {
        return resp.data;
    }).catch(error => {
        return "exception=" + error;
    });
    return result;
}

//get请求
function getRequst(url) {
    var result = axios({
        method: 'get',
        url: url
    }).then(function (resp) {
        return resp.data;
    }).catch(function (error) {
        return "exception=" + error;
    });
    return result;
}

function uploadRequst (url, data)
{
  //封装表单数据对象
  var RequestData = new FormData()

  if(JSON.stringify(data.params) != "{}")
  {
    for(var key in data.params)
    {
      RequestData.append(key, data.params[key])
    }
  }

  let result =  axios({
      method: 'post',
      url:url,
      data:RequestData,
      headers:{'Content-Type': 'multipart/form-data'},
      cancelToken: new CancelToken(c => {
        cancel = c
      })
    }).then(res => {
      resolve(res)
    })
    return result;
}